import { Node, instantiate, Prefab, Pool } from "cc";

export class PoolManager {
    private static _instance: PoolManager;
    public static get instance() {
        if (!this._instance) {
            this._instance = new PoolManager();
        } 
        return this._instance;
    }

    private constructor() {
        
    }

    private _pools: Map<string, Pool<Node>> = new Map();

    public getNode(prefab: Prefab) {
        if (!this._pools.has(prefab.name)) {
            const pool = new Pool<Node>(() => {
                const node = instantiate(prefab);
                return node;
            }
            , 10, (node: Node) => {
                node.destroy();
            });
            this._pools.set(prefab.name, pool);
        }
        return this._pools.get(prefab.name).alloc();
    }

    public putNode(node: Node) {
        node.removeFromParent();
        if (this._pools.has(node.name)) {
            this._pools.get(node.name).free(node);
        }
    }

    public clear() {
        for (const pool of this._pools.values()) {
            pool.destroy();
        }
        this._pools.clear(); 
    }


}